package com.longge;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    private StringBuilder sb = new StringBuilder();

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            sb.append("#").append(",");
            return sb.toString();
        }
        sb.append(root.val).append(",");
        serialize(root.left);
        serialize(root.right);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] node = data.split(",");
        return dfs(node, 0, node.length - 1);
    }

    private TreeNode dfs(String[] node, int i, int length) {
        if (i > length) return null;
        if (node[i].equals("#")) return null;
        TreeNode root = new TreeNode(Integer.parseInt(node[i]));
        root.left = dfs(node, i + 1, length);
        root.right = dfs(node, i + 1, length);
        return root;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode3.left = treeNode4;
        treeNode3.right = treeNode5;

        Codec codec = new Codec();
        TreeNode deserialize = codec.deserialize(codec.serialize(treeNode1));
        System.out.println(deserialize);
    }
}